﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgramMain.Classifiers;
using ProgramMain.Database;
using ProgramMain.Framework;
using ProgramMain.Database.SimpleOpticNetDBTableAdapters;

namespace ProgramMain.OpticNet
{

    public partial class CableBoxList : ProgramMain.Framework.BaseGridListCtl
    {
        public CableBoxList()
        {
            InitializeComponent();
        }

        private CableBoxKinds m_CableBoxKind = CableBoxKinds.CableBox;
        public CableBoxKinds CableBoxKind
        {
            get { return m_CableBoxKind; }
            set { m_CableBoxKind = value; }
        }

        protected override bool IsLoadDelayed()
        {
            return !DetailID.HasValue || Present == PresentFormType.InCableBoxes;
        }

        protected override void LoadData()
        {
            //прочитать данные из базы и заполнить датасет
            this.cableBoxesTableAdapter.SelectCommandTimeout = ProgramMain.Properties.Settings.Default.LongQueryTimeout;
            if (DetailID.HasValue)
            {
                switch (Present)
                {
                    case PresentFormType.InVertexes:
                        this.cableBoxesTableAdapter.Fill(this.simpleOpticNetDB.CableBoxes, null, DetailID, Convert.ToInt32(m_CableBoxKind));
                        break;
                    case PresentFormType.InCableBoxes:
                        this.cableBoxesTableAdapter.Fill(this.simpleOpticNetDB.CableBoxes, DetailID, null, Convert.ToInt32(m_CableBoxKind));
                        break;
                }
            }
            else
            {
                if (Present == PresentFormType.InCableBoxes)
                    this.cableBoxesTableAdapter.Fill(this.simpleOpticNetDB.CableBoxes, null, DetailID, Convert.ToInt32(m_CableBoxKind));
                else
                    simpleOpticNetDB.CableBoxes.Clear();

            }
            UpdateStatusText(this.simpleOpticNetDB.CableBoxes);
        }

        protected override void UpdateData()
        {
            //внести изменения в базу
            this.cableBoxesTableAdapter.SetUpdateTimeout = ProgramMain.Properties.Settings.Default.LongQueryTimeout;
            this.cableBoxesTableAdapter.Update(this.simpleOpticNetDB.CableBoxes);
            UpdateStatusText(this.simpleOpticNetDB.CableBoxes);
        }

        override protected BaseModalDetailCtl CreateDetailDialog(BaseModalDetailCtl.ShowModeTypes pShowMode)
        {
            return new CableBoxDetail(m_CableBoxKind);
        }

        override protected void PreCreateDetailDialog(BaseModalDetailCtl.ShowModeTypes pShowMode, DataRowView RowView)
        {
            if (pShowMode == BaseModalDetailCtl.ShowModeTypes.Add && RowView != null && DetailID.HasValue)
            {
                SimpleOpticNetDB.CableBoxesRow row = (SimpleOpticNetDB.CableBoxesRow)RowView.Row;
                row.VertexID = DetailID.Value;
            }
        }

        private void CableBoxList_DetailIDChanged(object sender, DetailEventArgs e)
        {
            DBRead();
        }

        protected override void biDetails_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (Present)
            {
                case PresentFormType.InVertexes:
                    if (Framework.BaseSecurity.CheckSecurityViewAction())
                    {
                        FrmCableBoxes frmCableBoxes = FrmCableBoxes.ShowForm(false);
                        frmCableBoxes.SetActiveCableBox(ViewRowID.Value);
                    }
                    break;
                case PresentFormType.InCableBoxes:
                    if (Framework.BaseSecurity.CheckSecurityViewAction())
                    {
                        FrmVertexes frmVertexes = FrmVertexes.ShowForm();
                        if (dataSource.Current != null)
                        {
                            SimpleOpticNetDB.CableBoxesRow row =
                                (SimpleOpticNetDB.CableBoxesRow)((DataRowView)dataSource.Current).Row;
                            frmVertexes.SetActiveVertex(row.VertexID);
                            frmVertexes.SetTableActive(Present);
                        }
                    }
                    break;
            }
        }

        public int? AddCableBox(int vertexID)
        {
            if (!CheckSecurityEditAction()) return null;
            CableBoxDetail dialog = new CableBoxDetail(m_CableBoxKind);
            SimpleOpticNetDB.CableBoxesRow row;
            try
            {
                dataSource.MoveLast();

                dialog.dataSource = dataSource;
                dialog.dataSource.AddNew();
                row = (SimpleOpticNetDB.CableBoxesRow)((DataRowView)dialog.dataSource.Current).Row;
                row.VertexID = vertexID;
                row.ModuleCount = 1;
                row.FibreCount = 1;
                
                row.UserID = ProgramMain.Framework.BaseSecurity.UserID.ToString();
            }
            catch (Exception)
            {
                XtraMessageBox.Show("Произошла ошибка при добавлении муфты в колодец.", "Ошибка", MessageBoxButtons.OK);
                return null;
            }
            DialogResult dlgRes = dialog.ShowModal(BaseModalDetailCtl.ShowModeTypes.Add);
            if (dlgRes == DialogResult.OK)
                try
                {
                    cableBoxesTableAdapter.Update(row);
                    return row.ID;

                }
                catch (Exception)
                {
                    XtraMessageBox.Show("Произошла ошибка при добавлении муфты в колодец.", "Ошибка", MessageBoxButtons.OK);

                }
            return null;
        }

        public int? AddCableBox(int vertexID, int fibreCount, string caption)
        {
            if (!CheckSecurityEditAction()) return null;
            SimpleOpticNetDB.CableBoxesRow row;
            try
            {
                CurveElementTypesTableAdapter elementTypesTableAdapter = new CurveElementTypesTableAdapter();
                elementTypesTableAdapter.ClearBeforeFill = true;
                elementTypesTableAdapter.SelectCommandTimeout = Properties.Settings.Default.LongQueryTimeout;
                SimpleOpticNetDB.CurveElementTypesDataTable elementTypesDataTable = elementTypesTableAdapter.GetData(Convert.ToInt32(m_CableBoxKind));
                List<SimpleOpticNetDB.CurveElementTypesRow> e = (from q in elementTypesDataTable.Cast<SimpleOpticNetDB.CurveElementTypesRow>() where q.FibreCount > fibreCount select q).ToList().OrderBy(f=>f.FibreCount).ToList();
                if(e.Count == 0) return null;

                dataSource.AddNew();
                row = (SimpleOpticNetDB.CableBoxesRow)((DataRowView)this.dataSource.Current).Row;
                row.VertexID = vertexID;
                row.ModuleCount = 1;
                row.FibreCount = fibreCount;
                row.CurveElementTypeID = e[0].ID;
                row.Caption = caption;
                row.UserID = ProgramMain.Framework.BaseSecurity.UserID.ToString();

                dataSource.EndEdit();
                cableBoxesTableAdapter.SetUpdateTimeout = ProgramMain.Properties.Settings.Default.LongQueryTimeout;
                cableBoxesTableAdapter.Update(simpleOpticNetDB.CableBoxes);
                return row.ID;

            }
            catch (Exception)
            {
                XtraMessageBox.Show("Произошла ошибка при добавлении муфты в колодец.", "Ошибка", MessageBoxButtons.OK);
            }
            return null;
        }

        public void DeleteCableBox()
        {
            Action_Delete(this, EventArgs.Empty);
        }

        protected override void biConnection_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dataSource.Current == null) return;
            try
            {
                SimpleOpticNetDB.CableBoxesRow cableBoxesRow =
                    (SimpleOpticNetDB.CableBoxesRow)((DataRowView)dataSource.Current).Row;

                FrmFibrePointDetail fibrePointDetail = new FrmFibrePointDetail();
                fibrePointDetail.VertexID = cableBoxesRow.VertexID;
                fibrePointDetail.VertexName = string.Format("{0}", cableBoxesRow.Vertex);
                fibrePointDetail.EquipVertexID = cableBoxesRow.ID;
                fibrePointDetail.ShowForm();
            }
            catch (Exception)
            {

            }

        }

        protected override void biVertexMap_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dataSource.Current == null) return;
            try
            {
                SimpleOpticNetDB.CableBoxesRow cableBoxesRow =
                    (SimpleOpticNetDB.CableBoxesRow)((DataRowView)dataSource.Current).Row;

                FrmVertexMap.ShowForm(false, cableBoxesRow.VertexID);
            }
            catch (Exception)
            {

            }
        }

        protected override void biAddDocument_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dataSource.Current != null)
            {
                SimpleOpticNetDB.CableBoxesRow row = (SimpleOpticNetDB.CableBoxesRow)((DataRowView)dataSource.Current).Row;
                new DocumentList() { CurveElementID = row.ID }.AddDocument();

            }
        }

        protected override void biDocumentList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dataSource.Current != null)
            {
                SimpleOpticNetDB.CableBoxesRow row = (SimpleOpticNetDB.CableBoxesRow)((DataRowView)dataSource.Current).Row;
                new FrmDocumentList() { CurveElementID = row.ID }.ShowDialog();
            }
        }
    }
}
